<script setup lang="ts">
import type { JobItem } from '@/apis/model/job.ts'
import {
  getComputeJobListApi,
  postComputeJobRetryApi,
} from '@/apis/modules/job.ts'
import { commonTableProps } from '@/utils/table.ts'
import TaskStatus from '@/views/dev-ops-monitor/task-monitor/components/TaskStatus.vue'
import { Message } from '@arco-design/web-vue'
import useConfig from './useConfig.ts'

const router = useRouter()
const queryParams = ref({
  start_time: '',
  end_time: '',
})

const { searchSchema, tableColumns } = useConfig()

const {
  data: tableData,
  loading,
  pagination,
  run,
} = useListRequest(getComputeJobListApi, {
  params: queryParams,
  immediate: true,
})

const { createSortChange } = useTable(run, tableData)
const onSortChange = createSortChange(queryParams)

const dateRange = ref<string[]>([])
watch(dateRange, () => {
  const [start, end] = dateRange.value || []
  queryParams.value.start_time = start || ''
  queryParams.value.end_time = end ? (Number(end) + 86400).toString() : ''
  run()
})

function toDetailPage(id: string) {
  router.push({ name: 'DevOpsMonitorTaskDetails', params: { id } })
}

function handleRetry(job: JobItem) {
  ModalHelper.confirm({
    title: '重试执行',
    content: '确定重试执行该任务吗？',
    async onOk() {
      await postComputeJobRetryApi({
        id: job.id,
        order_id: job.order_id,
        app_id: job.app_id,
      })
      await run()
      Message.success('操作成功')
    },
  })
}
</script>

<template>
  <main-container
    v-model:pagination="pagination"
    :loading="loading"
    @run="run"
  >
    <template #header>
      <a-range-picker
        v-model="dateRange"
        show-time
        value-format="X"
        :placeholder="['选择开始时间', '选择结束时间']"
        class="w-100!"
      >
        <template #suffix-icon>
          <i-icons-calendar class="mt-1" />
        </template>
      </a-range-picker>
      <multiple-condition-search
        v-model="queryParams"
        :schema="searchSchema"
        @search="run"
      />
    </template>
    <a-table
      v-bind="commonTableProps"
      :columns="tableColumns"
      :data="tableData"
      @sorter-change="onSortChange"
    >
      <template #status="{ record }">
        <task-status
          :status="record.status"
          @retry="handleRetry(record)"
        />
      </template>
      <template #actions="{ record }">
        <a-link @click="toDetailPage(record.order_id)">
          <i-icons-eye class="16" />
        </a-link>
      </template>
    </a-table>
  </main-container>
</template>
